package com.bjpowernode.service.impl;

import com.bjpowernode.dao.OrderDao;
import com.bjpowernode.dao.UserDao;
import com.bjpowernode.exception.GlobalException;
import com.bjpowernode.service.OrderService;
import com.bjpowernode.user.Order;
import com.bjpowernode.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private UserDao userDao;

    @Override
    public int insertOrder(Order order) {
        return orderDao.insertOrder(order);
    }

    @Override
    public int takeOrder(String username, Integer orderId) {
        User selectUser = userDao.selectUser(username);
        return orderDao.takeOrder(selectUser.getId(), orderId);
    }

    @Override
    public int modifyOrder(Integer orderId) {
        Order order = orderDao.selectById(orderId);
        if (order.getIsDel() == 1)
            throw new GlobalException("接单失败，此订单已被取消");
        return orderDao.modifyOrder(orderId);
    }

    @Override
    public int cancelOrder(Integer orderId) {
        Order order = orderDao.selectById(orderId);
        if (order.getIsTakeOrder() == 1)
            throw new GlobalException("此订单已有配送员接单，无法取消");
        return orderDao.cancelOrder(orderId);
    }

    @Override
    public List<Order> findProviderOrder(Integer id) {
        return orderDao.findProviderOrder(id);
    }

    @Override
    public List<Order> loadNoTakeOrder() {
        return orderDao.loadNoTakeOrder();
    }

    @Override
    public List<Order> loadUserOrder(String name) {
        User user = userDao.selectUser(name);
        return orderDao.loadUserOrder(user.getId());
    }

    @Override
    public List<Order> loadUserTakeOrder(String username) {
        User selectUser = userDao.selectUser(username);
        return orderDao.loadUserTakeOrder(selectUser.getId());
    }
}
